package vipers

import (
	"fmt"
	"ginchat/utils/errorx"
	"ginchat/utils/message"
	"sync"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

var (
	dbViper *viper.Viper
	dbOnce  sync.Once
)

func GetDatabaseViper() *viper.Viper {
	dbOnce.Do(func() {
		dbViper = viper.New()
		dbViper.AddConfigPath("./configs")
		dbViper.SetConfigType("yaml")
		dbViper.SetConfigName("database")

		if err := dbViper.ReadInConfig(); err != nil {
			errorx.ErrorExit(err)
		}

		dbViper.OnConfigChange(func(in fsnotify.Event) {
			msg := fmt.Sprintf("%s do %s", in.Name, in.Op)
			message.Println("database config file has been changed. ", msg)
		})
	})
	return dbViper
}
